package com.jsgt.greekfire.ui.mine.coindetail.transfer

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.scan.android.CaptureActivity
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ToastUtils
import com.ftd.livepermissions.LivePermissions
import com.ftd.livepermissions.PermissionResult
import com.jsgt.greekfire.BuildConfig
import com.jsgt.greekfire.R
import com.jsgt.greekfire.WALLET_ADDRESS
import com.jsgt.greekfire.ZERO_COMPARE
import com.jsgt.greekfire.bean.AddressBean
import com.jsgt.greekfire.bean.AssetsBean
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.ui.mine.user.address.AddressActivity
import com.jsgt.greekfire.viewmodel.CoinViewModel
import kotlinx.android.synthetic.main.activity_transfer.*
import org.greenrobot.eventbus.EventBus
import java.math.BigDecimal

/**
 * 转账
 * author fhx
 * create time 2020/4/24 19:31
 **/
class TransferActivity : BaseActivity() {
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }
    private var assetsBean: AssetsBean? = null
    private var addressBean: AddressBean? = null
    private var pwdDialog: SecurityPwdDialog? = null
    private var glbCharge = 0.0//扣除管理费金额
    private val DECODED_CONTENT_KEY = "codedContent"

    companion object {
        private const val REQUEST_CODE = 1001
        private const val REQUEST_CODE_SCAN = 1002
        const val ADDRESS_BEAN = "address_bean"
        private const val ASSETS_BEAN = "bean"
        fun start(context: Context, assetsBean: AssetsBean) {
            val intent = Intent(context, TransferActivity::class.java)
            intent.putExtra(ASSETS_BEAN, assetsBean)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_transfer
    var dotNumber = 4

    override fun main() {
        assetsBean = intent.getParcelableExtra(ASSETS_BEAN)
        title = "${assetsBean!!.assetName}转账"
//        if (TextUtils.equals("1", assetsBean!!.assetGuid)) {
//            dotNumber = 1
//        }

        setRightImage(R.mipmap.icon_scan).setOnClickListener {
            LivePermissions(this).request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            ).observe(this, Observer {
                when (it) {
                    is PermissionResult.Grant -> {
                        startActivityForResult(
                            Intent(this, CaptureActivity::class.java),
                            REQUEST_CODE_SCAN
                        )
                    }
                    is PermissionResult.Rationale -> {

                    }
                    is PermissionResult.Deny -> {
                        ToastUtils.show(this, "权限拒绝")
                    }
                }
            })
        }



        transfer_sum_et.numberDot = dotNumber
        transfer_sum_et.hint =
            "余额：${PriceFormatUtil.format(assetsBean!!.assetBalance!!, dotNumber)}"
        if (TextUtils.isEmpty(assetsBean!!.transfer_address)) {
            linearLayout11.visibility = View.GONE
        } else {
            send_address_tv.text = assetsBean!!.transfer_address
            linearLayout11.visibility = View.VISIBLE
        }
        address_book_iv.setOnClickListener {
            AddressActivity.start(this, AddressActivity.TRANSFER,
                REQUEST_CODE
            )
        }
        transfer_all_tv.setOnClickListener {
            if (TextUtils.equals("1", assetsBean!!.assetGuid)) {
                val allNum = BigDecimal(assetsBean!!.assetBalance!!.toString())
                transfer_sum_et.setText(PriceFormatUtil.format(allNum.toDouble(), dotNumber))
            } else {
                transfer_sum_et.setText(
                    PriceFormatUtil.format(
                        assetsBean!!.assetBalance!!,
                        dotNumber
                    )
                )
            }
        }
        confirm_tv.setOnClickListener {
            val num = transfer_sum_et.text.toString().trim()
            showDialog(num)
        }

        coinViewModel.getManagerCharge("1,2")
        coinViewModel.managerChargeLiveData.observe(this, Observer {
            for (i in it) {
                //管理币
                if (TextUtils.equals("1", assetsBean!!.assetGuid)) {
                    glbCharge = i.price!!.toDouble()
                    manage_tips_tv.text = "当前扣除GFC：${i.price}"
                    break
                }
            }
        })

        coinViewModel.transferLiveData.observe(this, Observer {

            ToastUtils.show(this, "提交成功")
            showProgress(false)
            val num = transfer_sum_et.text.toString().trim()
            var sum = num.toDouble()
            if (TextUtils.equals("1", assetsBean!!.assetGuid) &&
                assetsBean!!.assetBalance!! > glbCharge
            ) {
                //如果是管理币页面，则多扣0.1管理费
                sum = num.toDouble().plus(glbCharge)
            }
            EventBus.getDefault().post(TransferEvent("$sum"))
            finish()
        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
    }

    private fun showDialog(num: String) {
        if (TextUtils.isEmpty(num)) {
            ToastUtils.show(this, "数量不能为空")
            return
        }
        if (num.toDouble() < ZERO_COMPARE) {
            ToastUtils.show(this, "金额必须大于0")
            return
        }
        val address = transfer_address_et.text.toString()
        if (TextUtils.isEmpty(address)) {
            ToastUtils.show(this, "地址不能为空")
            return
        }
        if (BigDecimal(num).compareTo(BigDecimal(assetsBean!!.assetBalance!!.toString())) == 1) {
            ToastUtils.show(this, "余额不足")
            return
        }
        if (TextUtils.equals(address, WALLET_ADDRESS)) {
            ToastUtils.show(this, "不能给自己转账")
            return
        }

        if (!address.startsWith(BuildConfig.WALLET_PRIVATE_KEY_START) || address.length != 36) {
            ToastUtils.show(this, "转账地址有误")
            return
        }

        initDialog()
        pwdDialog?.nameTv!!.text = assetsBean!!.assetName
        pwdDialog?.numberTv!!.text = num
        pwdDialog?.show()

    }

    private fun transfer(pwd: String) {
        val num = transfer_sum_et.text.toString().trim()
        val address = transfer_address_et.text.toString()
        showProgress(true)

        coinViewModel.transferToAddress(
            num,
            assetsBean?.assetGuid!!,
            address, pwd
        )
    }

    private fun initDialog() {
        pwdDialog = SecurityPwdDialog(mContext!!, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                transfer(result)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE -> {
                    addressBean = data!!.getParcelableExtra(ADDRESS_BEAN)
                    transfer_address_et.setText(addressBean!!.addr)
                }
                REQUEST_CODE_SCAN -> {
                    val content = data?.getStringExtra(DECODED_CONTENT_KEY)
                    transfer_address_et.setText(content)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }
}